<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PayPal\CoreComponentTypes\BasicAmountType;
use PayPal\PayPalAPI\SetExpressCheckoutReq;
use PayPal\PayPalAPI\SetExpressCheckoutRequestType;
use PayPal\Service\PayPalAPIInterfaceServiceService;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

class IndexController extends Controller
{
    public function createOrder(Request $request)
    {
        $clientId = 'Af4_IeJxGXrU9_uYAm-Z2jfEoWS-FiiM-Nb7fPc2OkFJ5IIAYKWtedmqoHS36C-1gJX63TLrk1PrQBUi';
        $screct = 'EFLliRU7te3_cjIam0dz0x0i5Z55MjTwO6gnu5CI0qVRKjcc6ukoXh2f6CdiL-EPskNl5i9cOrcDUiJM';
        $environment = new SandboxEnvironment($clientId, $screct);
        $client = new PayPalHttpClient($environment);
        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = [
            "intent" => "CAPTURE",
            'purchase_units' =>
                array(
                    0 =>
                        array(
                            'reference_id' => 'PUHF',
                            'description' => 'Sporting Goods',
                            'custom_id' => 'CUST-HighFashions',
                            'soft_descriptor' => 'HighFashions',
                            'amount' =>
                                array(
                                    'currency_code' => 'USD',
                                    'value' => '220.00',
                                    'breakdown' =>
                                        array(
                                            'item_total' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '180.00',
                                                ),
                                            'shipping' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '20.00',
                                                ),
                                            'handling' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '10.00',
                                                ),
                                            'tax_total' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '20.00',
                                                ),
                                            'shipping_discount' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '10.00',
                                                ),
                                        ),
                                ),
                            'items' =>
                                array(
                                    0 =>
                                        array(
                                            'name' => 'T-Shirt',
                                            'description' => 'Green XL',
                                            'sku' => 'sku01',
                                            'unit_amount' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '90.00',
                                                ),
                                            'tax' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '10.00',
                                                ),
                                            'quantity' => '1',
                                            'category' => 'PHYSICAL_GOODS',
                                        ),
                                    1 =>
                                        array(
                                            'name' => 'Shoes',
                                            'description' => 'Running, Size 10.5',
                                            'sku' => 'sku02',
                                            'unit_amount' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '45.00',
                                                ),
                                            'tax' =>
                                                array(
                                                    'currency_code' => 'USD',
                                                    'value' => '5.00',
                                                ),
                                            'quantity' => '2',
                                            'category' => 'PHYSICAL_GOODS',
                                        ),
                                ),
                            'shipping' =>
                                array(
                                    'method' => 'United States Postal Service',
                                    'name' =>
                                        array(
                                            'full_name' => 'John Doe',
                                        ),
                                    'address' =>
                                        array(
                                            'address_line_1' => '123 Townsend St',
                                            'address_line_2' => 'Floor 6',
                                            'admin_area_2' => 'San Francisco',
                                            'admin_area_1' => 'CA',
                                            'postal_code' => '94107',
                                            'country_code' => 'US',
                                        ),
                                ),
                        ),
                ),

            "application_context" => [
                "cancel_url" => "https://example.com/cancel",
                "return_url" => "https://example.com/return"
            ]
        ];

        //  try {
        // Call API with your client and get a response for your call
        $response = $client->execute($request);
        // If call returns body in response, you can get the deserialized version from the result attribute of the response
        if ($response->statusCode == 201) {
            return response()->json(
                [
                    'code' => 'success',
                    'token' => $response->result->id
                ]
            );
        }
        /*  }catch (\HttpException $ex) {
              echo $ex->statusCode;
              print_r($ex->getMessage());
          }*/

    }

    public function ordersCaptureRequest(Request $request)
    {
        $request = new OrdersCaptureRequest($request->input('token'));
        $clientId = 'Af4_IeJxGXrU9_uYAm-Z2jfEoWS-FiiM-Nb7fPc2OkFJ5IIAYKWtedmqoHS36C-1gJX63TLrk1PrQBUi';
        $screct = 'EFLliRU7te3_cjIam0dz0x0i5Z55MjTwO6gnu5CI0qVRKjcc6ukoXh2f6CdiL-EPskNl5i9cOrcDUiJM';
        $environment = new SandboxEnvironment($clientId, $screct);
        $client = new PayPalHttpClient($environment);
        $request->prefer('return=representation');
        try {
            // Call API with your client and get a response for your call
            $response = $client->execute($request);
            // If call returns body in response, you can get the deserialized version from the result attribute of the response
            print_r($response);
        } catch (\HttpException $ex) {
            echo $ex->statusCode;
            print_r($ex->getMessage());
        }
    }

    public function setEc()
    {
        $config = array(
            'mode' => 'sandbox',
            'acct1.UserName' => 'jb-us-seller_api1.paypal.com',
            'acct1.Password' => 'WX4WTU3S8MY44S7F'
        );

        // Create request details
        $itemAmount = new BasicAmountType($currencyId, $amount);
        $setECReqType = new SetExpressCheckoutRequestType();
        $setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;

        // Create request
        $setECReq = new SetExpressCheckoutReq();
        $setECReq->SetExpressCheckoutRequest = $setECReqType;

        // Perform request
        $paypalService = new PayPalAPIInterfaceServiceService($config);
        $setECResponse = $paypalService->SetExpressCheckout($setECReq);

        // Check results
        if (strtoupper($setECResponse->Ack) == 'SUCCESS') {
            // Success
        }
    }

    public function wechat()
    {
        $app = \EasyWeChat::work();
        // $callbackUrl 为授权回调地址
        $callbackUrl = route('wechatCall',['redirect'=>config('mweb.web_url').'/#/login']); // 需设置可信域名

// 返回一个 redirect 实例
        $redirect = $app->oauth->redirect($callbackUrl);

// 获取企业微信跳转目标地址
        $targetUrl = $redirect->getTargetUrl();

// 直接跳转到企业微信授权
        $redirect->send();
    }
    public function wechatCall(Request  $request){
        $app = \EasyWeChat::work();
        $user = $app->oauth->detailed()->user();
        // 获取用户信息
        $user->getId(); // 对应企业微信英文名（userid）
        $user->getOriginal(); // 获取企业微信接口返回的原始信息
        return \Redirect::to($request->input('redirect').'?wechatCode='.$user->getId());
    }
}
